﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using Gollie.Extensions;
using Gollie.Database;
using Gollie.Mail;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;

using DrawingImage = System.Drawing.Image;

namespace Gollie.Controls
{
	public partial class ActivateAccount : BaseUserControl
	{
		UserInfo userInfo = null;

		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			this.Activate();
		}

		private void Activate()
		{
			try
			{
				string uid = this.ActivateUser();

				logger.Info("User {0} activated his account", uid);

//				this.Label1.Text = "Uw account is succesvol geactiveerd.";

				userInfo = UserInfo.GetUserInfo(uid);

				this.CreateQRCode();

				this.SendConfirmationMail(uid);

				Session["userinfo"] = userInfo;

//				this.Panel1.Visible = true;

				Response.Redirect("/Activated.aspx", true);
			}
			catch (Exception e)
			{
//				this.Panel1.Visible = false;

				this.Label1.Text = e.Message;
			}
		}

		private string ActivateUser()
		{
			string hashedUid = this.Request.QueryString["uid"];

			if (hashedUid == null || hashedUid.Length != 41 || hashedUid[0] != '*' || hashedUid.Substring(1).IsHex() == false)
				throw new Exception("U heeft geen toegang tot deze pagina.");

			string uid = Queries.ActivateUser(hashedUid);
			if (uid == null)
				throw new Exception("Dit account bestaat niet of is reeds geactiveerd.");

			return uid;
		}

		private void CreateQRCode()
		{
			string number = userInfo.QRCodeNumber;
			string encoded = Server.UrlEncode(Hash.Encrypt(number));

			string text = ConfigAppSettings.GetValue("CashierUrl") + "?c=" + encoded;

			QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
			QrCode code = encoder.Encode(text);
			GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

			int logoMargin = 6;
			int qrBorderWidth = 10;
			int extraHeight = 2 * logoMargin - qrBorderWidth;

			MemoryStream memStream = new MemoryStream();

			renderer.WriteToStream(code.Matrix, ImageFormat.Png, memStream);
			DrawingImage img = DrawingImage.FromStream(memStream);

			DrawingImage logo = DrawingImage.FromFile(Server.MapPath("/Images/LogoSmall.png"));

			Bitmap newImage = new Bitmap(img.Width, img.Height + logo.Height + extraHeight);
			Graphics g = Graphics.FromImage(newImage);
			g.DrawImage(img, 0, 0);

			RectangleF drawRect = new RectangleF(0, img.Height, img.Width, logo.Height + extraHeight);
			g.FillRectangle(Brushes.White, drawRect);

			g.DrawImage(logo, (img.Width - logo.Width) / 2, img.Height + extraHeight / 2);

			newImage.Save(userInfo.QRCodePath, ImageFormat.Png);

			g.Dispose();
			img.Dispose();
			newImage.Dispose();
			logo.Dispose();
		}

		private void SendConfirmationMail(string uid)
		{
			MailClient.Queue(new EMail
			{
				Name = "accountactivated",
				Recipients = userInfo.Email,
				//AttachmentPath = userInfo.QRCodePath,
				Args = new Dictionary<string, string>()
				{
											{ "{username}", uid },
											{ "{aanhef}", userInfo.MailAanhef },
											{ "{baseurl}", ConfigAppSettings.GetValue("baseurl") }
										    
				}
			});

		}
	
	}
}